<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

class StuController extends Controller{
    //首页
    public function index(){
        //控制器里面如何写路径；
        $path = public_path("uploads/123.txt");
        file_put_contents($path,"helloworld");

//        $list = DB::table('stu')->paginate(2);
//        return view('stu.index',['title'=>'首页','list'=>$list]);
    }
    //跳转到添加页面
    public function addview(){
        return view('stu.add',['title'=>'添加页面']);
    }
    //执行添加的方法
    public function doadd(Request $request){
        $data = array(
            'name' => $request->input('name'),
            'age' => $request->input('age'),
            'sex' => $request->input('sex'),
            'classid' => $request->input('classid'),
        );
        if(!empty($request->input('name'))){
            if(DB::table('stu')->insert($data)){
//            return redirect()->to('home');
                $url = url('home');
                echo "<script>alert('添加成功');window.location.href='{$url}'</script>";
            }
        }else{
//            return back()->withInput();
            $url = url('addview');
            echo "<script>alert('添加失败');window.location.href='{$url}'</script>";
        }
    }
    //删除数据的方法
    public function del($id){
        if(DB::table('stu')->delete($id)){
            $url = url('home');
            echo "<script>alert('删除成功');window.location.href='{$url}'</script>";
        }
    }
    //跳转到编辑界面
    public function editview($id){
        $list = DB::table('stu')->find($id);
        return view('stu.edit',['title'=>'编辑页面','list'=>$list]);
    }
    //执行修改的方法
    public function doedit(Request $request){
        $data = array(
            'id' => $request->input('id'),
            'name' => $request->input('name'),
            'age' => $request->input('age'),
            'sex' => $request->input('sex'),
            'classid' => $request->input('classid'),
        );
        if(!empty($request->input('name'))){
            if(DB::table('stu')->where('id',$request->input('id'))->update($data)){
                $url = url('home');
                echo "<script>alert('修改成功');window.location.href='{$url}'</script>";
            }
        }else{
//            return back()->withInput($data);
            $id = $request->input('id');
            $url = url('editview',['id'=>$id]);
            echo "<script>alert('修改成功2');window.location.href='{$url}'</script>";
        }

    }
}